package com.retail.lottery.colalottery.controller.callback;


import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.retail.lottery.colalottery.service.OrderCallBackMessageService;
import com.retail.lottery.colalottery.service.OrderCallbackService;
import com.retail.lottery.colalottery.vo.request.OrderCallBackFormVo;
import com.retail.lottery.colalottery.vo.request.OrderCallBackVo;
import com.retail.lottery.colalottery.vo.response.OrderCallBackResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

@RestController
@Slf4j
@RequestMapping("/v1/api/callback")
public class OrderDetailCallBackController {

    @Value("${exchange.rabbitmq.usingMq.flag}")
    private boolean usingMqFlag;
    @Resource
    private OrderCallBackMessageService orderCallBackMessageService;
    @Resource
    private OrderCallbackService orderCallBackService;

    @PostMapping(value = "/orderDataPostBack")
    public Object orderDataPostBack(HttpServletRequest request,
                                    @ModelAttribute("orderCallBackFormVo") OrderCallBackFormVo orderCallBackFormVo,
                                    BindingResult bindingResult) {
        log.info("订单回传入口日志2");
        OrderCallBackResponse response = new OrderCallBackResponse();
        if (bindingResult.hasErrors()) {
            log.error("订单数据回传参数获取失败错误,orderCallback:{}，ERROR：{}", JSON.toJSONString(orderCallBackFormVo), bindingResult.getFieldError().getDefaultMessage());
            return response;
        } else if (Objects.isNull(orderCallBackFormVo.getEncryptMobile())){
            //美团url监控发送空内容需返回http 200
            log.info("美团url监控发送空内容需返回http 200");
            return response;
        }
        log.info("订单数据回传开始处理,orderCallbackForm:{}", JSON.toJSONString(orderCallBackFormVo));

        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        try{
            OrderCallBackVo orderCallBack = buildOrderCallBackVo(orderCallBackFormVo);
            log.info("form change to vo,orderCallback:{}", JSON.toJSONString(orderCallBackFormVo));
            log.info("sign result:{}", orderCallBackService.checkMtSign(path,orderCallBackFormVo));
            //验签
//        OrderCallBackResponse response = new OrderCallBackResponse();
//        response.setResult_code(1);
//        return response;
//        if(!orderCallBackService.checkMtSign(path,orderCallBackFormVo)){
//            return ResultVO.error("签名验证失败");
//        }
            if(usingMqFlag){
                return orderCallBackMessageService.orderCallBackMessageEvent(orderCallBack);
            }else{
                return orderCallBackService.orderDataPostBack(orderCallBack);
            }
        }catch (Exception e){
            log.error("订单数据回传参数获取发送异常,orderCallback:{}，ERROR：{}", JSON.toJSONString(orderCallBackFormVo), e);
            return response;
        }
    }

    private OrderCallBackVo buildOrderCallBackVo(OrderCallBackFormVo orderCallBackFormVo) {
        OrderCallBackVo orderCallBack = new OrderCallBackVo();
        BeanUtils.copyProperties(orderCallBackFormVo, orderCallBack);
        String skuListEncodedStr = orderCallBackFormVo.getSkuList();
        String actIdentifierEncodedStr = orderCallBackFormVo.getActIdentifier();
        try {
            String skuListStr = URLDecoder.decode(skuListEncodedStr, String.valueOf(StandardCharsets.UTF_8));
            String actIdentifierStr = URLDecoder.decode(actIdentifierEncodedStr, String.valueOf(StandardCharsets.UTF_8));
            log.info(skuListStr); // 输出：["cola 1"]
            log.info(actIdentifierStr); // 输出：["cola 1"]
            if(StringUtils.isNotBlank(orderCallBackFormVo.getSkuList())){
                orderCallBack.setSkuInfos(JSON.parseArray(skuListStr, OrderCallBackVo.SkuInfo.class));
                orderCallBack.setActIdentifier(actIdentifierStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("订单数据回传参数获取失败错误,orderCallback:{}，ERROR：{}", JSON.toJSONString(orderCallBackFormVo), e.getMessage());
        }
        return orderCallBack;
    }
}
